"""Import header used by generated scripts when not embedding the full snippet.
This sets project root on sys.path and imports the helper API from src.bootstrap_helpers
so generated scripts can remain minimal (one-line import equivalent).
"""
from pathlib import Path
import sys

# Ensure project root is on sys.path so `from src.bootstrap_helpers import ...` works
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
try:
    from src.bootstrap_helpers import (
        start, end, progress, set_plot_style, detect_chinese_font,
        force_chinese_font, print_summary_table, log_saved, Parallel, delayed,
        get_logger, load_config_from_file
    )
except Exception:
    # If import fails (e.g., running as standalone), provide no-op fallbacks
    def get_logger(name: str = "gmt-template", level: str = "INFO"):
        import logging
        logger = logging.getLogger(name)
        if not logger.handlers:
            logger.addHandler(logging.StreamHandler())
        logger.setLevel(level)
        return logger

    def load_config_from_file(path: str = "config.yaml"):
        return {}

# ---- standalone template body starts here ----

"""
Standalone template for new scripts that will include the embedded bootstrap snippet when generated with --standalone.
Replace 烟雾测试-图表 with the desired title.
This template includes argparse for CLI standardization, config.yaml precedence, and uses logger from helpers.
"""

# 生成器会在脚本顶部（如需要）内联 bootstrap_snippet 或 import_header
from pathlib import Path
import sys
import os

# When running as standalone, assume project root is two levels up
ROOT = Path(__file__).resolve().parent.parent

# Try to obtain helpers; if they're not available (e.g., running the template outside the repo),
# provide minimal fallbacks so the template can still run in a limited way.
try:
    get_logger
except NameError:
    try:
        # if import_header was prepended it should set up sys.path
        from src.bootstrap_helpers import get_logger, load_config_from_file
    except Exception:
        def get_logger(name: str = "gmt-template", level: str = "INFO"):
            import logging
            logger = logging.getLogger(name)
            if not logger.handlers:
                logger.addHandler(logging.StreamHandler())
            logger.setLevel(level)
            return logger

        def load_config_from_file(path: str = "config.yaml"):
            return {}


def _build_argparse():
    import argparse
    parser = argparse.ArgumentParser(description='示例：独立脚本（包含模板的 argparse）')
    parser.add_argument('--dry-run', action='store_true', help='只运行到准备阶段，不写出文件或保存输出')
    parser.add_argument('--verbose', action='store_true', help='输出详细日志')
    parser.add_argument('--no-run', action='store_true', help='生成但不实际执行主要计算逻辑')
    parser.add_argument('--n-jobs', type=int, default=None, help='并行作业数，覆盖环境变量 N_JOBS')
    return parser


def main(argv=None):
    parser = _build_argparse()
    args = parser.parse_args(argv)

    # config precedence: config.yaml -> ENV vars -> CLI args
    try:
        cfg = load_config_from_file('config.yaml')
    except Exception:
        cfg = {}

    # logging
    log_level = 'DEBUG' if args.verbose else cfg.get('log_level', os.environ.get('LOG_LEVEL', 'INFO'))
    logger = get_logger('generated-script', level=log_level)

    TASK_LABEL = '烟雾测试-图表'

    # start
    _start = globals().get('start')
    start_time = None
    if callable(_start):
        try:
            start_time = _start(TASK_LABEL)
        except Exception:
            start_time = None
    else:
        logger.info('这是一个独立的示例脚本，包含内联引导代码')

    # Example computation or short-circuit if no-run
    if args.no_run:
        logger.info('no-run 模式，跳过主要计算')
        return

    import numpy as np
    import matplotlib.pyplot as plt

    # Apply plot style
    _sp = globals().get('set_plot_style')
    if callable(_sp):
        try:
            _sp()
        except Exception:
            pass

    # small example calculation
    x = np.linspace(0, 2*np.pi, 200)
    y = np.sin(x)

    # parallel example (respect args.n_jobs)
    try:
        USE_PARALLEL = str(os.environ.get('USE_PARALLEL', '')).lower() in ('1', 'true', 'yes', 'on')
    except Exception:
        USE_PARALLEL = False
    if args.n_jobs is not None:
        os.environ['N_JOBS'] = str(args.n_jobs)

    if USE_PARALLEL:
        try:
            _Parallel = globals().get('Parallel')
            _delayed = globals().get('delayed')
            if _Parallel is None or _delayed is None:
                from joblib import Parallel as _Parallel, delayed as _delayed
            inputs = list(range(10))
            _n = int(os.environ.get('N_JOBS', '2'))
            results = _Parallel(n_jobs=_n)(_delayed(lambda v: v*v)(i) for i in inputs)
            logger.info(f'并行示例结果（前5）：{results[:5]}')
        except Exception as e:
            logger.exception('并行示例失败，回退串行')

    fig, ax = plt.subplots()
    ax.plot(x, y, label='sin(x)')
    ax.set_title('示例：独立脚本的正弦曲线')
    ax.set_xlabel('时间 (s)')
    ax.set_ylabel('幅值')
    ax.legend()

    figures_dir = ROOT / 'figures'
    figures_dir.mkdir(parents=True, exist_ok=True)
    out = figures_dir / '独立示例.png'

    try:
        _det = globals().get('detect_chinese_font')
        _ff = globals().get('force_chinese_font')
        if callable(_det) and callable(_ff):
            fam = _det()
            try:
                from matplotlib.font_manager import FontProperties
                import matplotlib.font_manager as fm
                if fam:
                    fp = fm.findfont(FontProperties(family=fam))
                else:
                    fp = None
            except Exception:
                fp = None
            _ff(ax, fp or fam)
    except Exception:
        logger.debug('中文字体设置尝试失败')

    fig.savefig(out)
    logger.info(f'已保存示例图：{out}')

    _log_saved = globals().get('log_saved')
    try:
        if callable(_log_saved):
            _log_saved(out, TASK_LABEL)
    except Exception:
        logger.debug('调用 log_saved 失败')

    _print_table = globals().get('print_summary_table')
    try:
        import numpy as _np
        mean_v = float(_np.mean(y))
        std_v = float(_np.std(y))
        min_v = float(_np.min(y))
        max_v = float(_np.max(y))
        rows = [("示例曲线", mean_v, std_v, min_v, max_v)]
        cols = ["数据系列", "均值", "标准差", "最小值", "最大值"]
        if callable(_print_table):
            try:
                _print_table(rows, columns=cols, title="示例数据统计")
            except Exception:
                logger.debug('打印摘要表失败')
    except Exception:
        logger.debug('无法生成摘要表')

    _end = globals().get('end')
    if callable(_end) and start_time is not None:
        try:
            _end(start_time, TASK_LABEL)
        except Exception:
            logger.debug('结束时回调失败')


if __name__ == '__main__':
    main()
